package edu.nf.project.services.process.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.nf.project.entitys.entity.employeeAndCustomerInformation.convention.CustomerInfo;
import edu.nf.project.entitys.entity.employeeAndCustomerInformation.relevancy.CustomerInfo_Coupon;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.Board;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.CustomerOrder;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.CustomerOrderItem;
import edu.nf.project.entitys.enums.storeOperation.BoardStatusEnum;
import edu.nf.project.entitys.enums.storeOperation.OrderStatusEnum;
import edu.nf.project.mappers.employeeAndCustomerInformation.relevancy.CustomerInfo_CouponMapper;
import edu.nf.project.mappers.storeOperation.convention.BoardMapper;
import edu.nf.project.mappers.storeOperation.convention.CustomerOrderItemMapper;
import edu.nf.project.mappers.storeOperation.convention.CustomerOrderMapper;
import edu.nf.project.services.employeeAndCustomerInformation.CustomerInfoService;
import edu.nf.project.services.process.OrderProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author CSY
 * @date 2025 - 06 - 10
 * 订单处理器实现类
 * 实现对订单的处理
 */
@Component
public class OrderProcessImpl implements OrderProcess {
    @Autowired
    private CustomerOrderMapper customerOrderMapper;

    @Autowired
    private CustomerOrderItemMapper customerOrderItemMapper;

    @Autowired
    private BoardMapper boardMapper;

    @Autowired
    private CustomerInfo_CouponMapper infoCouponMapper;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Override
    public void processOrder(CustomerOrder order) {
        if (order.getOrderId() ==null){
            // 设置订单状态（假设初始状态为"待支付"）
            order.setOrderStatus(OrderStatusEnum.TO_BE_PAID);
            order.setPlaceOrderTime(new Date());

            // 执行插入，MyBatis会自动回填主键
            customerOrderMapper.insert(order);
        }else{
            customerOrderMapper.updateTotalAmount(order);
        }
    }

    @Override
    public void processOrderItems(List<CustomerOrderItem> orderItems,
                                  List<CustomerOrderItem> orderItemsAll,
                                  Integer orderId) {
        if (!orderItemsAll.isEmpty() || !orderItems.isEmpty()) {
            // 提取dishId用于快速查找
            Map<Integer, CustomerOrderItem> dbItemMap = orderItemsAll.stream()
                    .collect(Collectors.toMap(CustomerOrderItem::getDishId, item -> item));

            // 过滤并关联需要更新的订单项
            List<CustomerOrderItem> itemsToUpdate = orderItems.stream()
                    .filter(o -> dbItemMap.containsKey(o.getDishId()))
                    .peek(o -> o.setItemId(dbItemMap.get(o.getDishId()).getItemId()))
                    .toList();

            //过滤出添加的订单项
            List<CustomerOrderItem> itemsToAdd = orderItems.stream()
                    .filter(o -> orderItemsAll.stream()
                            .noneMatch(item -> item.getDishId().equals(o.getDishId())))
                    .toList();

            // 批量更新
            if (!itemsToUpdate.isEmpty()) {
                //根据订单项编号更新菜品购买的数量
                // 逐条更新
                for (CustomerOrderItem item : orderItems) {
                    CustomerOrderItem dbItem = dbItemMap.get(item.getDishId());
                    if (dbItem != null) {
                        // 更新数量
                        item.setItemId(dbItem.getItemId());
                        item.setQuantity(item.getQuantity() + dbItem.getQuantity());

                        // 单条更新
                        customerOrderItemMapper.updateById(item);
                    }
                }

            }

            if (!itemsToAdd.isEmpty()) {
                //订单项的所属订单，编号赋值
                itemsToAdd.forEach(orderItem -> orderItem.setOrderId(orderId));
                //循环将订单项添加到数据库
                itemsToAdd.forEach(orderItem -> customerOrderItemMapper.insert(orderItem));
            }
        }
    }

    @Override
    public void handlerCoupon(Integer couponId, Integer uId) {
        CustomerInfo customerInfo = customerInfoService.getCustomerByUserId(uId);
        //如果使用优惠券，使用后删除
        if (couponId!= 0) {
            QueryWrapper<CustomerInfo_Coupon> wrapper = new QueryWrapper<>();
            wrapper.eq("coupon_id", couponId)
                    .eq("customer_id",customerInfo.getCustomerId());
            // 2. 执行删除
            infoCouponMapper.delete(wrapper);
        }
    }

    @Override
    public void handlerBoardStatus(Integer borderId) {
        //getBoardId存在表示堂食
        if (borderId != null) {
            //如果是堂食修改餐桌状态
            Board board = new Board();
            board.setBoardId(borderId);
            board.setBoardStatus(BoardStatusEnum.REPAST);
            boardMapper.updateById(board);
        }
    }
}
